import { PureComponent } from "react";
import { Button, Modal,ActivityIndicator,InputItem,SearchBar,PullToRefresh,ListView } from "antd-mobile"
import { connect } from 'dva';
import { Row, Col } from 'antd';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import ReactDOM from 'react-dom';
import MToast from '../../components/Util/MToast';
@connect(() => {
  return ({

  })
})
export default class searchPage extends PureComponent{
  constructor(props){
    super(props);
    this.state = {
      goodsItem:[],
      value:'',
      loading:true,
      newsList:[],
      pages:{
        pageNum:1,
        pageSize:20
      },
      hasMore: true,
      refreshing: true,
      isLoading: true,
      height: document.documentElement.clientHeight-119,
      useBodyScroll: true,
      IsImage:false,
      data:[],
      leftData:[],
      rightData:[],
      noLogin:false,
    }
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: "",
        path: location.pathname + location.search
      }
    });
    if(localStorage[MI_APP_CODE + "phone"]==undefined){
      this.setState({
        noLogin:false
      })
    }else{
      this.setState({
        noLogin:true
      })
    }

  }
  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }
  }
  componentDidMount() {
    // const hei = this.state.height-100;
    // console.log(hei,this.state.height)
    // setTimeout(() => this.setState({
    //   height: hei,
    // }), 0);
  }
  componentDidMount() {
    // this.autoFocusInst.focus();
  }
  onChange= (value) => {
    this.setState({ value });
  };
  onRefresh = () => { //下拉刷新
    this.setState({ refreshing: true,  });

    setTimeout(() => {
      this.submit();
      this.setState({ refreshing: false });
    }, 600);
  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {//触底加载

  }
  getHW(data){
    let heightDate = [0,0];//接收累计高度的容器数组
    let rightData =[]//渲染右侧盒子的数组
    let leftData = []//渲染左侧盒子的数组
    data.forEach(item => {
      let height = 1;//对url地址进行一个截取，拿到高度
      let minNum = Math.min.apply(null,heightDate)// 从heighetData筛选最小项
      console.log(minNum)
      let minIndex = heightDate.indexOf(minNum);// 获取 最小项的小标 准备开始进行累加
      console.log(minIndex)
      heightDate[minIndex] = heightDate[minIndex] + height;//从 heightData 中找到最小的项后进行累加，
      if(minIndex===0){//[0]加到left [1]加到 right
        leftData.push(item)
      }else{
        rightData.push(item)
      }
    })
    this.setState({ leftData,rightData  });//重新set state
  }
  submit=()=>{
    let {dispatch,location} = this.props;
    let {value,loading} = this.state;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=app_search_goods_list",
          params: [
            {
              key: "keyword",
              value: value
            },
          ],
          _c: "app_search_goods_list"
        },
        callback: (result) => {
          let { data } = result;
          let {loading} = this.state;
          if(data==''){
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartNoGood),1, null, false);
          }else{

          }
          this.getHW(data) //调用
          this.setState({
            goodsItem:data,
            loading:false,
          })

        }
      }
    });
  }
  handleDetail=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/goodsDetail?id="+i.id+"&store_id="+i.store_id+"&status="+i.status }, isReplace: false })
  }
  handleAdd=(e,i)=>{
    // console.log(i);
    let {dispatch} = this.props;
    if(	localStorage[MI_APP_CODE + "phone"]==undefined){
      goToPage({ dispatch, config: { url: "/newLogin" }, isReplace: false })
      // MToast.info(T("您还未登录，请登录后操作",3, null, false));
    }else{dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "cart/add",
          params: [
            {
              key: "goods_id",
              value: i.id
            },
            {
              key: "goods_name",
              value: i.goods_name
            },
            {
              key: "img_url",
              value: i.img_url
            },
            {
              key: "price",
              value: i.price
            },
            {
              key: "quantity",
              value: 1
            }
          ]
        },
        callback: (result) => {
          let { data } = result;
          console.log(data)
          if(data.status=="0"){
            MToast.info(T(localeData[localStorage.locale].goodSold),1, null, false);
          }else{
            MToast.info(T(localeData[localStorage.locale].goodsDetailCartInfo),1, null, false);
          }

        }
      }
    })}

  }
  handleImageLoaded=()=>{
    let {IsImage} =this.state;
    this.setState({
      IsImage:true
    })
  }
  goodList() {
    let {leftData,rightData,goodsItem,IsImage} = this.state;

    if (!goodsItem || goodsItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div style={{overflow:'hidden'}}>
          <div className='left'>
            {
              leftData && leftData.map((item,index)=>{
                return     <div style={{marginBottom:'6%'}} >
                  <div  key={index} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
                    <div onClick={(e)=>{this.handleDetail(e,item)}}>
                      {IsImage?
                        <img src={handleOSS(item.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                        :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}

                    </div>
                    <div style={{overflow:'hidden'}}>
                      <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{item.goods_name}</p>
                      <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{item.price}</div>
                      <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,item) }}>
                        <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                      </div>
                    </div>

                    {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
                  </div>


                </div>
              })
            }
          </div>
          <div className='right'>
            {
              rightData && rightData.map((item,index)=>{
                return <div style={{marginBottom:'6%'}} >
                  <div  key={index} style={{background:'#fff',fontWeight:'bold',padding:'5% 5% 5%',borderRadius:'10px'}} className="item">
                    <div onClick={(e)=>{this.handleDetail(e,item)}}>
                      {IsImage?
                        <img src={handleOSS(item.img_url)} style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>
                        :<img src="image/falls.png" style={{width:'100%',height:'100%'}}   onLoad={this.handleImageLoaded}/>}

                    </div>
                    <div style={{overflow:'hidden'}}>
                      <p className="ellipsis2" style={{margin:'12px 0px 0px',textAlign:'left',color:'#595867',fontSize:'13px',height:'35px'}}>{item.goods_name}</p>
                      <div style={{float:'left',color:'#F09600',fontSize:'15px',marginTop:'5px'}}>€{item.price}</div>
                      <div style={{float:'right',width:'34px',height:'34px'}} onClick={(e) => {this.handleAdd(e,item) }}>
                        <img src="image/cart1.png" style={{width:'32px',height:'32px'}}/>
                      </div>
                    </div>

                    {/*<Button type="primary" size="small" inline style={{marginBottom:'1em'}} onClick={(e) => {this.handleAdd(e,i) }}>+ADD</Button>*/}
                  </div>


                </div>
              })
            }
          </div>
        </div>

      )

    }
  }

  render(){
    let {dispatch} = this.props;
    let {goodsItem,loading,IsImage,noLogin} = this.state;
    const messages = localeData[localStorage.locale];
    // if (loading) {
    //   return (
    //     <div className="normal">
    //       <ActivityIndicator toast text="正在加载" animating={true} />
    //     </div>
    //   )
    // }
    return(
      <IntlProvider
        locale={ this.state.locale } messages={messages}
      >
      <div style={{height:"100%",position: 'relative',background:'rgb(249, 247, 247)'}}>
        <Col span={2} style={{position:'fixed',top:'3px',right:'12px',zIndex:1000}}>
          {noLogin? <img src="image/cart10.png" style={{width:'40px',height:'40px'}}   onClick={() => {
            goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false })
          }}/>:<img src="image/cart10.png" style={{width:'40px',height:'40px'}}   onClick={() => {
            goToPage({ dispatch, config: { url: "/ungoodcart" }, isReplace: false })
          }}/>}
        </Col>
        <Row style={{padding:'13% 5% 3%'}}>
          <Col span={24}>
            <SearchBar
            placeholder={messages.search}
            maxLength={200}
            onChange={this.onChange}
            onSubmit={value => this.submit(value)}
              ref={ref => this.autoFocusInst = ref}
          /></Col>



        </Row>
        <PullToRefresh
          damping={60}
          ref={el => this.ptr = el}
          style={{
            height: this.state.height,
            overflow: 'auto',
          }}
          refreshing={this.state.refreshing}
          onRefresh={this.onRefresh}
        >
          {this.goodList()}
        </PullToRefresh>
      </div>
      </IntlProvider>
    )
  }
}
